package com.example.demo.common.utils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 一些通用方法
 */
public class CommonUtil {

    /**
     * 生成验证码图片
     * @param request 设置session
     * @param response 转成图片
     * @param captchaProducer 生成图片方法类
     * @param validateSessionKey session名称
     * @throws Exception
     */
    public static void validateCode(HttpServletRequest request, HttpServletResponse response, DefaultKaptcha captchaProducer, String validateSessionKey) throws Exception{
        // Set to expire far in the past.
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");

        // return a jpeg
        response.setContentType("image/jpeg");

        // create the text for the image
        String capText = captchaProducer.createText();

        // store the text in the session
        request.getSession().setAttribute(validateSessionKey, capText);

        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);

        ServletOutputStream out = response.getOutputStream();

        // write the data out
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }

    /**
     * 创建对应的导入模板
     * @param fileName 文件名
     * @param sheetName sheet的name
     * @param excelTitleArr 表格的表头
     * @param response
     */
    public void createExcelImpFile(String fileName,String sheetName,String[] excelTitleArr,HttpServletResponse response){
        try {
            response.setCharacterEncoding("UTF-8");
            fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
            HSSFWorkbook wb = new HSSFWorkbook();
            //Open Declaration org.apache.poi.hssf.usermodel.HSSFFont
            //org.apache.poi.hssf.usermodel.*;
            HSSFCellStyle btStyle = wb.createCellStyle();
            HSSFFont fontBt = wb.createFont();
            fontBt.setBold(true);
            fontBt.setFontHeightInPoints((short) 11);
            btStyle.setFont(fontBt);
            btStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
            btStyle.setBorderBottom(BorderStyle.THIN); // 下边框
            btStyle.setBorderLeft(BorderStyle.THIN);// 左边框
            btStyle.setBorderTop(BorderStyle.THIN);// 上边框
            btStyle.setBorderRight(BorderStyle.THIN);// 右边框
            //设置单元格为文本格式
            HSSFSheet sheet = wb.createSheet(sheetName);
            HSSFRow row0 = sheet.createRow(0);
            //学校名称\班级名称\姓名\身份证\学籍辅号\性别
            int rowNum = excelTitleArr.length;
            for(int i=0;i<rowNum;i++){
                sheet.setColumnWidth(i, 3500);
                HSSFCell cell = row0.createCell(i);
                cell.setCellStyle(btStyle);
                cell.setCellValue(excelTitleArr[i]);
            }
            // 生成文件Excel
            OutputStream ros = new BufferedOutputStream(response.getOutputStream());
            response.reset();
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            try {
                wb.write(ros);
                ros.close();
            } catch (IOException e) {
                //logger.error(e.getMessage(), e);
                e.printStackTrace();
            }
        } catch (Exception e) {
            //logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
    }

}
